"""
HR端API路由
提供简历分析、候选人筛选、职位管理等功能
"""

from fastapi import APIRouter, Depends, HTTPException, UploadFile, File, status
from sqlalchemy.orm import Session
from typing import List, Optional
import json
import os
from datetime import datetime

from ..dependencies import get_db, get_current_user
from ..models import (
    # 数据库模型
    User, Company, JobPosition, Resume, JobApplication, CandidateProfile,
    # Pydantic模型
    JobPositionCreate, JobPositionUpdate, JobPositionResponse,
    CandidateSearchRequest, CandidateMatchResult,
    ResumeAnalysisDetailResponse, BatchCandidateAnalysis, BatchAnalysisResult,
    ApplicationStatusUpdate, RecruitmentStatistics,
    GitHubVerificationRequest, GitHubVerificationResponse,
    SmartRecommendationRequest, SmartRecommendationResponse,
    HRFilterPreferences, UserResponse
)
from ....core.container import Container

router = APIRouter(prefix="/hr", tags=["HR端功能"])

@router.get("/dashboard/stats", response_model=RecruitmentStatistics)
async def get_recruitment_statistics(
    current_user: User = Depends(get_current_user),
    db: Session = Depends(get_db)
):
    """获取招聘统计数据"""
    if current_user.user_type != "hr":
        raise HTTPException(
            status_code=status.HTTP_403_FORBIDDEN,
            detail="只有HR用户可以访问此功能"
        )
    
    # 获取公司相关的申请统计
    company_id = current_user.company_id
    if not company_id:
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail="用户未关联公司"
        )
    
    # 统计各种申请状态的数量
    total_applications = db.query(JobApplication).join(JobPosition).filter(
        JobPosition.company_id == company_id
    ).count()
    
    pending_reviews = db.query(JobApplication).join(JobPosition).filter(
        JobPosition.company_id == company_id,
        JobApplication.status == "pending"
    ).count()
    
    interviews_scheduled = db.query(JobApplication).join(JobPosition).filter(
        JobPosition.company_id == company_id,
        JobApplication.status == "interview"
    ).count()
    
    offers_made = db.query(JobApplication).join(JobPosition).filter(
        JobPosition.company_id == company_id,
        JobApplication.status == "hired"
    ).count()
    
    # 计算转化率
    conversion_rates = {
        "application_to_interview": interviews_scheduled / max(total_applications, 1) * 100,
        "interview_to_offer": offers_made / max(interviews_scheduled, 1) * 100,
        "overall_success": offers_made / max(total_applications, 1) * 100
    }
    
    return RecruitmentStatistics(
        total_applications=total_applications,
        pending_reviews=pending_reviews,
        interviews_scheduled=interviews_scheduled,
        offers_made=offers_made,
        average_processing_time=2.5,  # 示例数据
        top_skills_demand=[
            {"skill": "Python", "demand": 85},
            {"skill": "React", "demand": 75},
            {"skill": "SQL", "demand": 70}
        ],
        conversion_rates=conversion_rates
    )

@router.post("/jobs", response_model=JobPositionResponse)
async def create_job_position(
    job_data: JobPositionCreate,
    current_user: User = Depends(get_current_user),
    db: Session = Depends(get_db)
):
    """创建新职位"""
    if current_user.user_type != "hr":
        raise HTTPException(
            status_code=status.HTTP_403_FORBIDDEN,
            detail="只有HR用户可以创建职位"
        )
    
    if not current_user.company_id:
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail="用户未关联公司"
        )
    
    job_position = JobPosition(
        company_id=current_user.company_id,
        title=job_data.title,
        description=job_data.description,
        requirements=job_data.requirements,
        experience_level=job_data.experience_level.value,
        salary_range=job_data.salary_range,
        location=job_data.location,
        employment_type=job_data.employment_type
    )
    
    db.add(job_position)
    db.commit()
    db.refresh(job_position)
    
    return job_position

@router.get("/jobs", response_model=List[JobPositionResponse])
async def get_company_jobs(
    current_user: User = Depends(get_current_user),
    db: Session = Depends(get_db),
    limit: int = 20,
    offset: int = 0
):
    """获取公司所有职位"""
    if current_user.user_type != "hr":
        raise HTTPException(
            status_code=status.HTTP_403_FORBIDDEN,
            detail="只有HR用户可以访问此功能"
        )
    
    if not current_user.company_id:
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail="用户未关联公司"
        )
    
    jobs = db.query(JobPosition).filter(
        JobPosition.company_id == current_user.company_id
    ).offset(offset).limit(limit).all()
    
    return jobs

@router.put("/jobs/{job_id}", response_model=JobPositionResponse)
async def update_job_position(
    job_id: int,
    job_data: JobPositionUpdate,
    current_user: User = Depends(get_current_user),
    db: Session = Depends(get_db)
):
    """更新职位信息"""
    if current_user.user_type != "hr":
        raise HTTPException(
            status_code=status.HTTP_403_FORBIDDEN,
            detail="只有HR用户可以更新职位"
        )
    
    job = db.query(JobPosition).filter(
        JobPosition.id == job_id,
        JobPosition.company_id == current_user.company_id
    ).first()
    
    if not job:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="职位不存在"
        )
    
    # 更新字段
    update_data = job_data.dict(exclude_unset=True)
    for field, value in update_data.items():
        if hasattr(job, field):
            setattr(job, field, value)
    
    db.commit()
    db.refresh(job)
    
    return job

@router.post("/candidates/search", response_model=List[CandidateMatchResult])
async def search_candidates(
    search_request: CandidateSearchRequest,
    current_user: User = Depends(get_current_user),
    db: Session = Depends(get_db),
    container: Container = Depends(lambda: Container())
):
    """智能候选人搜索和匹配"""
    if current_user.user_type != "hr":
        raise HTTPException(
            status_code=status.HTTP_403_FORBIDDEN,
            detail="只有HR用户可以搜索候选人"
        )
    
    # 构建搜索查询
    query_parts = []
    if search_request.skills:
        query_parts.append(f"技能要求: {', '.join(search_request.skills)}")
    if search_request.experience_level:
        query_parts.append(f"经验等级: {search_request.experience_level}")
    if search_request.location:
        query_parts.append(f"工作地点: {search_request.location}")
    
    search_query = "寻找候选人，" + "，".join(query_parts)
    
    # 使用智能体进行候选人搜索和分析
    task_config = {
        "description": "候选人搜索和匹配分析",
        "query": search_query,
        "search_criteria": search_request.dict(),
        "task_type": "candidate_search"
    }
    
    try:
        orchestrator = container.orchestrator()
        result = await orchestrator.orchestrate_task(task_config)
        
        # 解析结果并返回匹配的候选人
        candidates = []
        if result.get("status") == "completed":
            search_results = result.get("result", {}).get("candidates", [])
            
            for candidate_data in search_results[:search_request.limit]:
                candidate_match = CandidateMatchResult(
                    candidate=candidate_data.get("profile", {}),
                    match_score=candidate_data.get("match_score", 0.0),
                    matching_skills=candidate_data.get("matching_skills", []),
                    missing_skills=candidate_data.get("missing_skills", []),
                    strengths=candidate_data.get("strengths", []),
                    recommendations=candidate_data.get("recommendations", [])
                )
                candidates.append(candidate_match)
        
        return candidates
        
    except Exception as e:
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=f"候选人搜索失败: {str(e)}"
        )

@router.post("/resumes/{resume_id}/analyze", response_model=ResumeAnalysisDetailResponse)
async def analyze_resume_detailed(
    resume_id: int,
    current_user: User = Depends(get_current_user),
    db: Session = Depends(get_db),
    container: Container = Depends(lambda: Container()),
    job_position_id: Optional[int] = None
):
    """详细分析简历"""
    if current_user.user_type != "hr":
        raise HTTPException(
            status_code=status.HTTP_403_FORBIDDEN,
            detail="只有HR用户可以分析简历"
        )
    
    # 获取简历信息
    resume = db.query(Resume).filter(Resume.id == resume_id).first()
    if not resume:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="简历不存在"
        )
    
    # 获取职位要求（如果提供）
    job_requirements = ""
    if job_position_id:
        job = db.query(JobPosition).filter(
            JobPosition.id == job_position_id,
            JobPosition.company_id == current_user.company_id
        ).first()
        if job:
            job_requirements = f"职位: {job.title}\n要求: {', '.join(job.requirements)}\n描述: {job.description}"
    
    # 构建分析任务
    task_config = {
        "description": "全面简历分析评估",
        "resume_content": json.dumps(resume.parsed_content, ensure_ascii=False),
        "job_requirements": job_requirements,
        "analysis_depth": "comprehensive",
        "task_type": "resume_analysis"
    }
    
    try:
        orchestrator = container.orchestrator()
        result = await orchestrator.orchestrate_task(task_config)
        
        if result.get("status") == "completed":
            analysis_data = result.get("result", {})
            
            # 更新简历的分析结果
            resume.analysis_result = analysis_data
            resume.score = analysis_data.get("overall_score", 0.0)
            db.commit()
            
            return ResumeAnalysisDetailResponse(
                resume_id=resume_id,
                analysis_result=analysis_data,
                score=analysis_data.get("overall_score", 0.0),
                strengths=analysis_data.get("strengths", []),
                weaknesses=analysis_data.get("weaknesses", []),
                suggestions=analysis_data.get("suggestions", []),
                skill_assessment=analysis_data.get("skill_assessment", {}),
                experience_evaluation=analysis_data.get("experience_evaluation", {}),
                background_verification=analysis_data.get("background_verification", {}),
                potential_prediction=analysis_data.get("potential_prediction", {})
            )
        else:
            raise HTTPException(
                status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
                detail="简历分析失败"
            )
            
    except Exception as e:
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=f"简历分析失败: {str(e)}"
        )

@router.post("/candidates/batch-analyze", response_model=BatchAnalysisResult)
async def batch_analyze_candidates(
    batch_request: BatchCandidateAnalysis,
    current_user: User = Depends(get_current_user),
    db: Session = Depends(get_db),
    container: Container = Depends(lambda: Container())
):
    """批量分析候选人"""
    if current_user.user_type != "hr":
        raise HTTPException(
            status_code=status.HTTP_403_FORBIDDEN,
            detail="只有HR用户可以批量分析候选人"
        )
    
    # 获取候选人信息
    candidates = db.query(CandidateProfile).filter(
        CandidateProfile.id.in_(batch_request.candidate_ids)
    ).all()
    
    if len(candidates) != len(batch_request.candidate_ids):
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail="部分候选人不存在"
        )
    
    # 获取职位要求（如果提供）
    job_requirements = ""
    if batch_request.job_position_id:
        job = db.query(JobPosition).filter(
            JobPosition.id == batch_request.job_position_id,
            JobPosition.company_id == current_user.company_id
        ).first()
        if job:
            job_requirements = f"职位: {job.title}\n要求: {', '.join(job.requirements)}"
    
    # 构建批量分析任务
    batch_id = f"batch_{datetime.now().strftime('%Y%m%d_%H%M%S')}"
    
    task_config = {
        "description": "批量候选人分析",
        "candidates": [
            {
                "id": c.id,
                "profile": {
                    "name": c.full_name,
                    "skills": c.skills,
                    "experience": c.experience_years,
                    "location": c.location
                }
            } for c in candidates
        ],
        "job_requirements": job_requirements,
        "analysis_depth": batch_request.analysis_depth,
        "batch_id": batch_id,
        "task_type": "batch_analysis"
    }
    
    try:
        orchestrator = container.orchestrator()
        result = await orchestrator.orchestrate_task(task_config)
        
        if result.get("status") == "completed":
            analysis_results = result.get("result", {}).get("analyses", [])
            
            return BatchAnalysisResult(
                batch_id=batch_id,
                total_candidates=len(candidates),
                processed_count=len(analysis_results),
                results=analysis_results,
                summary_statistics=result.get("result", {}).get("summary", {})
            )
        else:
            raise HTTPException(
                status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
                detail="批量分析失败"
            )
            
    except Exception as e:
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=f"批量分析失败: {str(e)}"
        )

@router.put("/applications/{application_id}/status")
async def update_application_status(
    application_id: int,
    status_update: ApplicationStatusUpdate,
    current_user: User = Depends(get_current_user),
    db: Session = Depends(get_db)
):
    """更新申请状态"""
    if current_user.user_type != "hr":
        raise HTTPException(
            status_code=status.HTTP_403_FORBIDDEN,
            detail="只有HR用户可以更新申请状态"
        )
    
    # 获取申请信息
    application = db.query(JobApplication).join(JobPosition).filter(
        JobApplication.id == application_id,
        JobPosition.company_id == current_user.company_id
    ).first()
    
    if not application:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="申请不存在"
        )
    
    # 更新状态
    application.status = status_update.status.value
    if status_update.hr_feedback:
        application.hr_feedback = status_update.hr_feedback
    if status_update.interview_notes:
        application.interview_notes = status_update.interview_notes
    application.updated_at = datetime.utcnow()
    
    db.commit()
    
    return {"message": "申请状态已更新", "status": application.status}

@router.post("/github/verify", response_model=GitHubVerificationResponse)
async def verify_github_profile(
    verification_request: GitHubVerificationRequest,
    current_user: User = Depends(get_current_user),
    container: Container = Depends(lambda: Container())
):
    """验证GitHub档案"""
    if current_user.user_type != "hr":
        raise HTTPException(
            status_code=status.HTTP_403_FORBIDDEN,
            detail="只有HR用户可以验证GitHub档案"
        )
    
    task_config = {
        "description": "GitHub档案验证和代码质量分析",
        "github_url": verification_request.github_url,
        "candidate_id": verification_request.candidate_id,
        "task_type": "github_verification"
    }
    
    try:
        orchestrator = container.orchestrator()
        result = await orchestrator.orchestrate_task(task_config)
        
        if result.get("status") == "completed":
            verification_data = result.get("result", {})
            
            return GitHubVerificationResponse(
                is_valid=verification_data.get("is_valid", False),
                repository_stats=verification_data.get("repository_stats", {}),
                code_quality_score=verification_data.get("code_quality_score", 0.0),
                star_count=verification_data.get("star_count", 0),
                contribution_analysis=verification_data.get("contribution_analysis", {}),
                technology_stack=verification_data.get("technology_stack", []),
                activity_level=verification_data.get("activity_level", "unknown")
            )
        else:
            raise HTTPException(
                status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
                detail="GitHub验证失败"
            )
            
    except Exception as e:
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=f"GitHub验证失败: {str(e)}"
        )

@router.post("/recommendations", response_model=SmartRecommendationResponse)
async def get_smart_recommendations(
    recommendation_request: SmartRecommendationRequest,
    current_user: User = Depends(get_current_user),
    container: Container = Depends(lambda: Container())
):
    """获取智能推荐"""
    if current_user.user_type != "hr":
        raise HTTPException(
            status_code=status.HTTP_403_FORBIDDEN,
            detail="只有HR用户可以获取推荐"
        )
    
    task_config = {
        "description": "智能推荐生成",
        "user_id": recommendation_request.user_id,
        "recommendation_type": recommendation_request.recommendation_type,
        "context": recommendation_request.context or {},
        "task_type": "smart_recommendation"
    }
    
    try:
        orchestrator = container.orchestrator()
        result = await orchestrator.orchestrate_task(task_config)
        
        if result.get("status") == "completed":
            recommendation_data = result.get("result", {})
            
            return SmartRecommendationResponse(
                recommendations=recommendation_data.get("recommendations", []),
                reasoning=recommendation_data.get("reasoning", []),
                confidence_scores=recommendation_data.get("confidence_scores", []),
                personalization_factors=recommendation_data.get("personalization_factors", [])
            )
        else:
            raise HTTPException(
                status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
                detail="推荐生成失败"
            )
            
    except Exception as e:
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=f"推荐生成失败: {str(e)}"
        )

@router.get("/applications", response_model=List[dict])
async def get_job_applications(
    current_user: User = Depends(get_current_user),
    db: Session = Depends(get_db),
    job_id: Optional[int] = None,
    status: Optional[str] = None,
    limit: int = 20,
    offset: int = 0
):
    """获取职位申请列表"""
    if current_user.user_type != "hr":
        raise HTTPException(
            status_code=status.HTTP_403_FORBIDDEN,
            detail="只有HR用户可以查看申请"
        )
    
    query = db.query(JobApplication).join(JobPosition).filter(
        JobPosition.company_id == current_user.company_id
    )
    
    if job_id:
        query = query.filter(JobApplication.job_position_id == job_id)
    if status:
        query = query.filter(JobApplication.status == status)
    
    applications = query.offset(offset).limit(limit).all()
    
    return [
        {
            "id": app.id,
            "job_title": app.job_position.title,
            "candidate_name": app.resume.candidate.full_name if app.resume.candidate else "Unknown",
            "status": app.status,
            "match_score": app.match_score,
            "applied_at": app.applied_at,
            "resume_id": app.resume_id
        }
        for app in applications
    ]

@router.post("/preferences", response_model=dict)
async def update_hr_preferences(
    preferences: HRFilterPreferences,
    current_user: User = Depends(get_current_user),
    db: Session = Depends(get_db)
):
    """更新HR筛选偏好"""
    if current_user.user_type != "hr":
        raise HTTPException(
            status_code=status.HTTP_403_FORBIDDEN,
            detail="只有HR用户可以更新偏好设置"
        )
    
    # 获取或创建HR档案
    hr_profile = db.query(current_user.hr_profile).first()
    if not hr_profile:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="HR档案不存在"
        )
    
    # 更新偏好设置
    hr_profile.preferences = preferences.dict()
    db.commit()
    
    return {"message": "偏好设置已更新", "preferences": hr_profile.preferences}